package com.huan.hadoop.serializable;

import lombok.Getter;
import lombok.Setter;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Objects;

/**
 * 编写流量统计的Java Bean
 * 1、作为MapReduce 的 Value时，需要实现 Writable 接口
 * 2、作为MapReduce 的 Key时，需要实现 Comparable 接口， 必须使用 WritableComparable 接口，否则报错
 *
 * @author huan.fu
 * @date 2023/7/10 - 19:20
 */
@Getter
@Setter
public class PhoneFlow implements WritableComparable<PhoneFlow> {

    /**
     * 手机号，当作key的排序使用
     */
    private String phone;

    /**
     * 上行流量
     */
    private long upFlow;
    /**
     * 下行流量
     */
    private long downFlow;
    /**
     * 总流量
     */
    private long sumFlow;

    /**
     * 实现序列化操作
     */
    @Override
    public void write(DataOutput out) throws IOException {
        out.writeUTF(this.phone);
        out.writeLong(this.upFlow);
        out.writeLong(this.downFlow);
        out.writeLong(this.sumFlow);
    }

    /**
     * 实现反序列化操作
     */
    @Override
    public void readFields(DataInput in) throws IOException {
        this.phone = in.readUTF();
        this.upFlow = in.readLong();
        this.downFlow = in.readLong();
        this.sumFlow = in.readLong();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        PhoneFlow phoneFlow = (PhoneFlow) o;
        return upFlow == phoneFlow.upFlow && downFlow == phoneFlow.downFlow && sumFlow == phoneFlow.sumFlow && Objects.equals(phone, phoneFlow.phone);
    }

    @Override
    public int compareTo(PhoneFlow o) {
        return -Integer.compare(this.getPhone().hashCode(), o.getPhone().hashCode());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this);
    }

    @Override
    public String toString() {
        return this.getUpFlow() + "\t" + this.getDownFlow() + "\t" + this.getSumFlow();
    }
}
